import { message, Button, Form, Input, Space, Popconfirm } from "antd";
import CommonModal from '@/components/CommonModal';
import { useEffect, useState } from "react";
import { quickQueryLabelSaveOrUpdate } from './service.js';
import { CloseCircleFilled } from "@ant-design/icons";
import styles from './index.module.less';

//快捷查询弹框
const QuickSearchModal = ({ formData, quickList, quickSearchCode, handleOk,  handleCancel}) => {

  const [open, setOpen] = useState(false);

  const [form] = Form.useForm();

  const [isOk, setIsOk] = useState(false);

  const [saveData, setSaveData] = useState([]);

  useEffect(() => {
    setOpen(true);
  }, [])

  const onOk = () => {
    form.validateFields().then(val => {
      if(val) {
        saveQuickSearch();
      }
    }).catch(err => {
      console.log(err, 'err');
    })
  }

  //保存快捷查询
  const saveQuickSearch = async () => {
    START_LOADING();
    const arr = [ ...quickList, { title: form.getFieldValue('title'), param: formData}];
    const params = {
      code: quickSearchCode,
      param: JSON.stringify(arr)
    }
    const { success, data } = await quickQueryLabelSaveOrUpdate(params);
    END_LOADING();
    if(success) {
      setSaveData(JSON.parse(data.param));
      setOpen(false);
      setIsOk(true);
    }
  }

  const onCancel = () => {
    setOpen(false);
  }

  const afterClose = () => {
    handleCancel();
    if(isOk) {
      handleOk(saveData);
    }
  }

  const defaultValue = `常用搜索条件${Number(quickList.length) + 1}`

  return (
    <CommonModal
      title="另存为快捷查询条件"
      width="520px"
      open={open}
      onOk={onOk}
      onCancel={onCancel}
      afterClose={afterClose}
    >
      <Form
        form={form}
        initialValues={{
          title: defaultValue
        }}
        name="quick-search-modal-form"
        autoComplete="false"
      >
        <Form.Item name="title" rules={[{ required: true, message: '请输入快捷查询名称' }]}>
          <Input placeholder="快捷查询名称" showCount maxLength={10} />
        </Form.Item>
      </Form>
    </CommonModal>
  )

}

//快捷查询设置
const QuickSearch = ({ form, maxCount = 5, quickList, ignoreQuickKeys, quickSearchCode, setQuickList, clickQuickSearch }) => {

  const [showModal, setShowModal] = useState(false);

  //点击当前快捷查询条件
  const handleClickQuickSearch = (val) => {
    clickQuickSearch(val);
  }

  //删除快捷查询
  const deleteQuickSearch = async (index) => {
    const arr = [ ...quickList ];
    arr.splice(index, 1);
    START_LOADING();
    const { success, data } = await quickQueryLabelSaveOrUpdate({
      code: quickSearchCode,
      param: JSON.stringify(arr)
    })
    if(success) {
      setQuickList(JSON.parse(data.param));
    }
    END_LOADING();
  }

  //点击另存为快捷查询
  const handleSaveQuickSearch = () => {
    if(quickList.length >= maxCount) {
      return message.warning(`搜索条件保存${maxCount}个配置，请删除后再尝试`);
    }
    const formData = form.getFieldsValue();
    let btn = false;
    for (let i in formData) {
      if (!ignoreQuickKeys.includes(i) && (formData[i] || formData[i] == 0)) {
        btn = true;
        break;
      }
    }
    if (btn) {
      setShowModal(true);
    } else {
      message.warning('当前搜索条件为空，无需保存');
    }
  }

  //快捷查询
  const QuickSearchModalProps = {
    formData: form.getFieldsValue(),
    quickSearchCode,
    quickList,
    handleOk(data) {
      setQuickList(data);
    },
    handleCancel() {
      setShowModal(false);
    }
  }

  return (
    <Space size={8}>
      <Button
        style={{ width: '100px', padding: 0, fontSize: '12px'}}
        onClick={handleSaveQuickSearch}
      >
        另存为快捷查询
      </Button>
      {
        quickList.map((v, index) => {
          return (
            <div key={index} className={styles.quickWrap} onClick={() => handleClickQuickSearch(v.param)}>
              {v.title}
              <Popconfirm title="是否确认删除当前快捷查询" onConfirm={() => deleteQuickSearch(index)}>
                <CloseCircleFilled onClick={e => e.stopPropagation() } className={styles.anticonOpera}  />
              </Popconfirm>
            </div>
          )
        })
      }
      {showModal && <QuickSearchModal {...QuickSearchModalProps} />}
    </Space>
  )
}

export default QuickSearch;